package com.sbwebsocket.core.redis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sbwebsocket.core.model.bo.TopicMessageBody;
import com.sbwebsocket.core.redis.model.contants.WsMessageRedisKeyPrefix;
import com.sbwebsocket.core.service.MessageQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 广播消息
 * @Auther: GSJ
 * @Date: 2022/2/10
 * @Description:
 * @version: 1.0
 */
@Slf4j
public class RedisTopicMessageQueue implements MessageQueue<TopicMessageBody> {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RedisModeUtil redisModeUtil;

    @Override
    public boolean delivery(TopicMessageBody messageBody) {
        //先把消息扔到广播队列中
        try {
            //todo: 考虑优化把消息发送到各自对应的key为:WsMessageRedisKeyPrefix.SERVER_MSG_FANOUT+hostKey对应的消息队列中,以减少无用数据循环
            redisTemplate.convertAndSend(WsMessageRedisKeyPrefix.SERVER_MSG_TOPIC_QUEUE,objectMapper.writeValueAsString(messageBody));
            return true;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return false;
    }



}
